package com.glink.manage.service.Impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.common.contants.BaseCodeConstants;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.common.AuthorizationUtils;
import com.glink.manage.common.CommonUtils;
import com.glink.manage.common.Constants;
import com.glink.manage.common.GrantCodeUtil;
import com.glink.manage.common.sm.Sm4Encryption;
import com.glink.manage.domain.*;
import com.glink.manage.dto.constructionwork.*;
import com.glink.manage.mapper.ConstructionWorkSiteMapper;
import com.glink.manage.service.*;
import com.glink.manage.vo.constructionwork.*;
import com.glink.manage.vo.participatingunit.ParticipatingUnitListVO;
import com.glink.manage.vo.participatingunit.ParticipatingUnitSimpleDetailInfoVO;
import com.glink.manage.vo.person.PersonSimplePhoneInfoVO;
import com.glink.manage.vo.view.SiteWeatherVO;
import com.glink.manage.vo.weather.PlaceNameQueryListVO;
import com.glink.manage.vo.weather.PlaceNameQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author  qiushaoshan
 * @since 2025-01-08
 */
@Service
@Slf4j
public class ConstructionWorkSiteServiceImpl extends ServiceImpl<ConstructionWorkSiteMapper, ConstructionWorkSiteBean> implements ConstructionWorkSiteService {

//    @Value("${env.serialNumber:}")
//    private String serialNumber;
    @Value("${env.serialNumberUrl: http://192.168.1.31:1117/getSerialNumber}")
    private String serialNumberUrl;
    
    @Value("${env.privateKey: R/xEKlitzBo61B2LNS6bMhTugW4lnYLlFfXX6dvkyYQ=}")
    private String privateKey;

    @Value("${grant.name.suffix:（未授权）}")
    private String unauthorizedSuffix;
    
    @Autowired
    private OrgService orgService;
    
    @Autowired
    private ConstructionWorkUnitRelaService constructionWorkUnitRelaService;
    
    @Autowired
    private ParticipatingUnitService participatingUnitService;
    
    @Autowired
    @Lazy
    private PersonManageService personManageService;
    
    @Autowired
    private WeatherService weatherService;

    @Autowired
    private BlacklistService blacklistService;
    @Autowired
    private UserServiceImpl userServiceImpl;

    /**
     * 根据施工工程ID查询工程现场个数
     *
     * @param constructionWorkObjId 施工工程ID
     * @return 数量
     */
    @Override
    public Integer countByConstructionWorkObjId(String constructionWorkObjId) {
        return this.lambdaQuery()
                .eq(ConstructionWorkSiteBean::getConstructionWorkObjId, constructionWorkObjId)
                .eq(ConstructionWorkSiteBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
//                .isNotNull(ConstructionWorkSiteBean::getGrantCode)
                .count();
    }

    /**
     * 分页查询工程现场
     *
     * @param dto 查询信息
     * @return 工程现场
     */
    @Override
    public IPage<ConstructionWorkSitePageVO> findSiteByPage(ConstructionWorkSitePageDTO dto) {
        IPage<ConstructionWorkSiteBean> constructionWorkUnitRelaBeanIPage = new Page<>(dto.getPage(), dto.getSize());

        IPage<ConstructionWorkSiteBean> workSiteBeanIPage = this.baseMapper.findSiteByPage(constructionWorkUnitRelaBeanIPage, dto.getConstructionWorkObjId());

        IPage<ConstructionWorkSitePageVO> simpleInfoVOIPage = new Page<>(workSiteBeanIPage.getCurrent(), workSiteBeanIPage.getSize(), workSiteBeanIPage.getTotal());
        List<ConstructionWorkSitePageVO> simpleInfoVOList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(workSiteBeanIPage.getRecords())){
            workSiteBeanIPage.getRecords().forEach(obj -> {
                ConstructionWorkSitePageVO simpleInfoVO = new ConstructionWorkSitePageVO();
                simpleInfoVO.setObjId(obj.getObjId());
                simpleInfoVO.setSiteName(getNewSiteName(obj));
                simpleInfoVO.setStatus(obj.getStatus());
                simpleInfoVO.setSuperintendent(obj.getSuperintendent());
                simpleInfoVO.setContactNumber(obj.getContactNumber());
                simpleInfoVO.setIfGrant(obj.getIfGrant());
                //查询授权码
                if(StringUtils.isBlank(obj.getGrantCode())){
                    simpleInfoVO.setIfGrant(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
                }else {
                    try {
                        String serialNumber = obj.getObjId() + "-" + getSerialNumber();
                        GrantCodeUtil.checkPeriodValidity(privateKey, obj.getGrantCode(), serialNumber);
                        simpleInfoVO.setIfGrant(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                    } catch (GeneralSimpleException e) {
                        simpleInfoVO.setIfGrant(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
                    }
                }
                
                // 负责人名称
                if(StringUtils.isNotBlank(simpleInfoVO.getSuperintendent())){
                    simpleInfoVO.setSuperintendentName(personManageService.findNameByObjId(simpleInfoVO.getSuperintendent()));
                }
                
                simpleInfoVOList.add(simpleInfoVO);
            });
            simpleInfoVOIPage.setRecords(simpleInfoVOList);
        }

        return simpleInfoVOIPage;
    }

    /**
     * 保存工程现场
     *
     * @param dto 保存信息
     * @return 保存状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String saveSite(ConstructionWorkSiteSaveDTO dto) {
        ConstructionWorkSiteBean siteBean = new ConstructionWorkSiteBean();
        siteBean.setSiteName(dto.getSiteName());
        siteBean.setConstructionWorkObjId(dto.getConstructionWorkObjId());
        siteBean.setIfDelete(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
        siteBean.setStatus(dto.getStatus());
        siteBean.setSuperintendent(dto.getSuperintendent());
        siteBean.setContactNumber(dto.getContactNumber());

        siteBean.setArea(dto.getArea());
        siteBean.setDistric(dto.getDistric());
        siteBean.setProv(dto.getProv());
        siteBean.setAreaCode(dto.getAreaCode());
        siteBean.setAreaid(dto.getAreaid());
        
        siteBean.setObjId(BaseCommonUtils.generateUUID());
        boolean status = save(siteBean);
        if(status){
            return siteBean.getObjId();
        }
        return null;
    }

    /**
     * 移除工程现场
     *
     * @param dto 工程现场ID
     * @return 移除状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean delSite(ConstructionWorkSiteIdDTO dto) {
        
        return lambdaUpdate()
                .set(ConstructionWorkSiteBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                .set(ConstructionWorkSiteBean::getGrantCode, null)
                .eq(ConstructionWorkSiteBean::getObjId, dto.getObjId())
                .update();
    }

    /**
     * 根据用户所属单位查询参建单位
     *
     * @param orgId 单位ID
     * @return 参建单位
     */
    @Override
    public List<ParticipatingUnitListVO> findUnitByWorkAndOrgId(String orgId) throws GeneralSimpleException {
        List<String> orgIdList = orgService.findOrgTreeIdByOrgId(orgId);
        if(CollectionUtils.isNotEmpty(orgIdList)){
            List<ConstructionWorkSiteBean> workSiteBeanList = this.lambdaQuery()
                    .in(ConstructionWorkSiteBean::getObjId, orgIdList)
                    .in(ConstructionWorkSiteBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
//                    .isNotNull(ConstructionWorkSiteBean::getGrantCode)
                    .list();
            if(CollectionUtils.isNotEmpty(workSiteBeanList)){
                List<String> workIdList = workSiteBeanList.stream().map(ConstructionWorkSiteBean::getObjId).collect(Collectors.toList());
                List<String> unitIdList = constructionWorkUnitRelaService.findUnitIdByWorkIdIn(workIdList);
                if(CollectionUtils.isNotEmpty(unitIdList)){
                    return participatingUnitService.findListByObjIdIn(unitIdList, true);
                }
            }
        }
        
        return null;
    }


    /**
     * 根据工程id查询施工现场列表
     * @param workObjId 工程ID
     * @return 工程现场
     */
    @Override
    public List<ConstructionWorkSiteListVO> findWorkSiteListByWorkId(String workObjId) {
        List<ConstructionWorkSiteListVO> workSiteListVOList = Lists.newArrayList();
        List<ConstructionWorkSiteBean> constructionWorkSiteBeanList = this.lambdaQuery()
                .eq(ConstructionWorkSiteBean::getConstructionWorkObjId, workObjId)
                .eq(ConstructionWorkSiteBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
//                .isNotNull(ConstructionWorkSiteBean::getGrantCode)
                .list();
        if (CollectionUtils.isNotEmpty(constructionWorkSiteBeanList)){
            constructionWorkSiteBeanList.forEach(constructionWorkSiteBean -> {
                        ConstructionWorkSiteListVO constructionWorkSiteListVO = new ConstructionWorkSiteListVO();
                        constructionWorkSiteListVO.setConstructionWorkSiteObjId(constructionWorkSiteBean.getObjId());
                        constructionWorkSiteListVO.setConstructionWorkSiteName(getNewSiteName(constructionWorkSiteBean));
                        constructionWorkSiteListVO.setIfGrant(constructionWorkSiteBean.getIfGrant());
                        workSiteListVOList.add(constructionWorkSiteListVO);
                    });
        }
        return workSiteListVOList;
    }

    /**
     * 根据施工现场ID查询施工现场名称
     *
     * @param constructionWorkSiteObjId 施工现场ID
     * @return 施工现场名称
     */
    @Override
    public String findNameByObjId(String constructionWorkSiteObjId) {
        ConstructionWorkSiteBean constructionWorkSiteBean = this.lambdaQuery()
                .eq(ConstructionWorkSiteBean::getObjId, constructionWorkSiteObjId)
//                .isNotNull(ConstructionWorkSiteBean::getGrantCode)
                .one();
        if(Objects.nonNull(constructionWorkSiteBean)){
            return getNewSiteName(constructionWorkSiteBean);
        }
        return null;
    }

    /**
     * 场站新名称
     * @param constructionWorkSiteBean 施工现场
     * @return 场站新名称
     */
    @Override
    public String getNewSiteName(ConstructionWorkSiteBean constructionWorkSiteBean){
        String siteName = constructionWorkSiteBean.getSiteName();
        String grantStatus = constructionWorkSiteBean.getIfGrant();
        String grantCode = constructionWorkSiteBean.getGrantCode();
        if(StringUtils.isNotBlank(siteName)){
            if(StringUtils.equals(grantStatus, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01) && StringUtils.isNotBlank(grantCode)){
                return siteName;
            }else{
                // 未授权场站增加后缀
                return siteName + unauthorizedSuffix;    
            }
        }else{
            return siteName;
        }
    }

    /**
     * 根据施工现场ID查询负责人ID
     *
     * @param constructionWorkSiteObjId 施工现场ID
     * @return 负责人
     */
    @Override
    public String findSuperintendentByObjId(String constructionWorkSiteObjId) {
        ConstructionWorkSiteBean constructionWorkSiteBean = getById(constructionWorkSiteObjId);
        if(Objects.nonNull(constructionWorkSiteBean)){
            return constructionWorkSiteBean.getSuperintendent();
        }
        return null;
    }

    /**
     * 根据施工现场ID查询工程ID
     *
     * @param constructionWorkSiteObjId 施工现场ID
     * @return 工程ID
     */
    @Override
    public String findWorkIdByObjId(String constructionWorkSiteObjId) {
        ConstructionWorkSiteBean constructionWorkSiteBean = getById(constructionWorkSiteObjId);
        if(Objects.nonNull(constructionWorkSiteBean)){
            return constructionWorkSiteBean.getConstructionWorkObjId();
        }
        return null;
    }

    /**
     * 根据地名查询地市信息
     *
     * @param dto 查询条件
     * @return 地市信息
     */
    @Override
    public List<ConstructionWorkSitePlaceNameVO> findPlaceName(ConstructionWorkSitePlaceNameDTO dto) {
        List<ConstructionWorkSitePlaceNameVO> placeNameVOList = Lists.newArrayList();
        PlaceNameQueryVO placeNameQueryVO = weatherService.getPlaceNameByArea(dto.getArea());
        
        if(Objects.nonNull(placeNameQueryVO)){
            List<PlaceNameQueryListVO> queryListVOList = placeNameQueryVO.getList();
            if(CollectionUtils.isNotEmpty(queryListVOList)){
                queryListVOList.forEach(placeNameQueryListVO -> {
                    ConstructionWorkSitePlaceNameVO placeNameVO = new ConstructionWorkSitePlaceNameVO();
                    placeNameVO.setProv(placeNameQueryListVO.getProv());
                    placeNameVO.setArea(placeNameQueryListVO.getArea());
                    placeNameVO.setDistric(placeNameQueryListVO.getDistric());
                    placeNameVO.setAreaCode(placeNameQueryListVO.getAreaCode());
                    placeNameVO.setAreaid(placeNameQueryListVO.getAreaid());
                    placeNameVOList.add(placeNameVO);
                });
            }
        }
        return placeNameVOList;
    }

    /**
     * 查询施工现场信息
     *
     * @param dto 施工现场ID
     * @return 施工现场信息
     */
    @Override
    public ConstructionWorkSiteInfoVO findSite(ConstructionWorkSiteIdDTO dto) {
        ConstructionWorkSiteBean constructionWorkSiteBean = getById(dto.getObjId());
        if(Objects.nonNull(constructionWorkSiteBean)){
            ConstructionWorkSiteInfoVO siteInfoVO = new ConstructionWorkSiteInfoVO();
            BeanUtils.copyProperties(constructionWorkSiteBean, siteInfoVO);

            //查询授权码
            if(StringUtils.isBlank(constructionWorkSiteBean.getGrantCode())){
                siteInfoVO.setIfGrant(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
            }else {
                try {
                    String serialNumber = constructionWorkSiteBean.getObjId() + "-" + getSerialNumber();
                    GrantCodeUtil.checkPeriodValidity(privateKey, constructionWorkSiteBean.getGrantCode(), serialNumber);
                    siteInfoVO.setIfGrant(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                } catch (GeneralSimpleException e) {
                    siteInfoVO.setIfGrant(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
                }
            }
            return siteInfoVO;
        }
        return null;
    }

    /**
     * 更新施工现场
     *
     * @param dto 施工现场信息
     * @return 更新状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean updateSite(ConstructionWorkSiteUpdateDTO dto) {
        ConstructionWorkSiteBean siteBean = getById(dto.getObjId());
        if(Objects.nonNull(siteBean)){
            siteBean.setSiteName(dto.getSiteName());
            siteBean.setConstructionWorkObjId(dto.getConstructionWorkObjId());
            siteBean.setIfDelete(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
            siteBean.setStatus(dto.getStatus());
            siteBean.setSuperintendent(dto.getSuperintendent());
            siteBean.setContactNumber(dto.getContactNumber());

            siteBean.setArea(dto.getArea());
            siteBean.setDistric(dto.getDistric());
            siteBean.setProv(dto.getProv());
            siteBean.setAreaCode(dto.getAreaCode());
            siteBean.setAreaid(dto.getAreaid());
            
            return updateById(siteBean);
        }
        return false;
    }

    /**
     * 查询天气
     *
     * @param constructionWorkSiteObjId 施工现场ID
     * @return 天气信息
     */
    @Override
    public SiteWeatherVO queryWeatherBySiteId(String constructionWorkSiteObjId) {

        SiteWeatherVO siteWeatherVO = null;
        ConstructionWorkSiteBean constructionWorkSiteBean = getById(constructionWorkSiteObjId);
        if(Objects.nonNull(constructionWorkSiteBean) && StringUtils.isNotBlank(constructionWorkSiteBean.getAreaCode())){
            siteWeatherVO = weatherService.findWeatherByAreaCode(constructionWorkSiteBean.getAreaCode());
        }
        return siteWeatherVO;
    }

    /**
     * 根据工程ID查询施工现场
     *
     * @param workIds 工程ID
     * @return 施工现场
     */
    @Override
    public List<ConstructionWorkSiteBean> findByWorkIdIn(List<String> workIds) {
        return this.lambdaQuery().in(ConstructionWorkSiteBean::getConstructionWorkObjId, workIds)
                .eq(ConstructionWorkSiteBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
//                .isNotNull(ConstructionWorkSiteBean::getGrantCode)
                .orderByAsc(ConstructionWorkSiteBean::getCreateTime)
                .orderByAsc(ConstructionWorkSiteBean::getObjId)
                .list();
    }

    /**
     * 获取施工现场机器码
     *
     * @param dto 查询条件
     * @return 机器码
     */
    @Override
    public ConstructionWorkSiteGrantVO findSiteMachineCode(ConstructionWorkSiteIdDTO dto) throws GeneralSimpleException {
        ConstructionWorkSiteGrantVO siteGrantVO = new ConstructionWorkSiteGrantVO();
        try {
            // 获取设备序号
            String serialNumber = getSerialNumber();
            ConstructionWorkSiteBean constructionWorkSiteBean = this.getById(dto.getObjId());
            if(Objects.nonNull(constructionWorkSiteBean)){
                String result = constructionWorkSiteBean.getObjId() + "-" + serialNumber + "-" + RandomStringUtils.randomAlphanumeric(4);
                siteGrantVO.setMachineCode(Sm4Encryption.encryptEcb(Constants.NUMBER_PUBLIC_KEY, result));
                siteGrantVO.setGrantCode(constructionWorkSiteBean.getGrantCode());
                return siteGrantVO;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取施工现场机器码失败，id:{}", dto.getObjId());
        }
        throw new GeneralSimpleException("500006");
    }

    /**
     * 授权施工现场
     *
     * @param dto 授权信息
     * @return 授权状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean grantSite(ConstructionWorkSiteGrantDTO dto) throws GeneralSimpleException {
        // 获取设备序号
        ConstructionWorkSiteBean constructionWorkSiteBean = this.getById(dto.getObjId());
        if(Objects.isNull(constructionWorkSiteBean)){
            return false;
        }

        String serialNumber = constructionWorkSiteBean.getObjId() + "-" + getSerialNumber();
        // 校验收取码
        GrantCodeUtil.checkPeriodValidity(privateKey, dto.getGrantCode(), serialNumber);

        constructionWorkSiteBean.setGrantCode(dto.getGrantCode());
        constructionWorkSiteBean.setIfGrant(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
        return this.updateById(constructionWorkSiteBean);
    }

    /**
     * 根据参建单位ID获取参建单位下的人员信息列表
     * @param dto 参建单位ID
     * @return 参建单位下的人员信息列表
     */
    @Override
    public List<PersonSimplePhoneInfoVO> findPersonManageInfoByUnitId(ConstructionWorkUnitIdDTO dto) throws GeneralSimpleException {
        List<PersonSimplePhoneInfoVO> personSimplePhoneInfoVOList = new ArrayList<>();
       //查询
        List<PersonManageBean> personManageBeanList = personManageService.lambdaQuery()
                .eq(PersonManageBean::getOrgId, dto.getObjId()).list();
        if(CollectionUtils.isNotEmpty(personManageBeanList)){
            personManageBeanList.forEach(personManageBean -> {
                PersonSimplePhoneInfoVO personSimplePhoneInfoVO = new PersonSimplePhoneInfoVO();
                BeanUtils.copyProperties(personManageBean, personSimplePhoneInfoVO);
                //未删除
                if (!StringUtils.equals(personManageBean.getIfDelete(),BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01) ){
                   //是否加入黑名单
                    Integer count = blacklistService.lambdaQuery().eq(BlacklistBean::getSourceObjId, personManageBean.getObjId()).count();
                    //加入黑名单
                    if(Objects.nonNull(count)&&count>0){
                        personSimplePhoneInfoVO.setIfBlacklist(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                    }else {//未加入黑名单
                        personSimplePhoneInfoVO.setIfBlacklist(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
                    }
                    //已开通账号
                    if (StringUtils.isNotEmpty(personManageBean.getAccountObjId())){
                        UserBean userBean = userServiceImpl.getById(personManageBean.getAccountObjId());
                        if(Objects.nonNull(userBean)){
                            //存在手机号
                            if (StringUtils.isNotEmpty(userBean.getPhone())){
                                personSimplePhoneInfoVO.setPhone(userBean.getPhone());
                            }
                        }
                    }
                    personSimplePhoneInfoVOList.add(personSimplePhoneInfoVO);
                }
            });
        }
        return personSimplePhoneInfoVOList;
    }

    /**
     * 根据施工工程-参建单位关联ID获取详细关联信息
     * @param dto 施工工程-参建单位关联ID
     * @return 详细关联信息
     */
    @Override
    public ParticipatingUnitSimpleDetailInfoVO findWorkUnitRealDetailInfoByUnitRealId(ConstructionWorkUnitRealIdDTO dto) {
        ParticipatingUnitSimpleDetailInfoVO participatingUnitSimpleDetailInfoVO=new ParticipatingUnitSimpleDetailInfoVO();
        ConstructionWorkUnitRelaBean constructionWorkUnitRelaBean = constructionWorkUnitRelaService.getById(dto.getObjId());
        if (Objects.nonNull(constructionWorkUnitRelaBean)){
            BeanUtils.copyProperties(constructionWorkUnitRelaBean, participatingUnitSimpleDetailInfoVO);
            if (StringUtils.isNotEmpty(constructionWorkUnitRelaBean.getParticipatingUnitObjId())){
                ParticipatingUnitBean participatingUnitBean = participatingUnitService.getById(constructionWorkUnitRelaBean.getParticipatingUnitObjId());
                if (Objects.nonNull(participatingUnitBean)){
                    participatingUnitSimpleDetailInfoVO.setUnitName(participatingUnitBean.getUnitName());
                }
            }
            if (StringUtils.isNotEmpty(constructionWorkUnitRelaBean.getResponsiblePersonId())){
                PersonManageBean personManageBean = personManageService.getById(constructionWorkUnitRelaBean.getResponsiblePersonId());
                if (Objects.nonNull(personManageBean)){
                    participatingUnitSimpleDetailInfoVO.setResponsibleName(personManageBean.getName());
                }
            }
        }
        return participatingUnitSimpleDetailInfoVO;
    }

    /**
     * 校验场站授权
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void checkSiteAuthorize() {
        List<ConstructionWorkSiteBean> constructionWorkSiteBeanList = this.lambdaQuery()
                .eq(ConstructionWorkSiteBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .isNotNull(ConstructionWorkSiteBean::getGrantCode).ne(ConstructionWorkSiteBean::getGrantCode, "")
                .list();
        if(CollectionUtils.isNotEmpty(constructionWorkSiteBeanList)){
            List<String> workSiteIdList = Lists.newArrayList();
            String tempSerialNumber = getSerialNumber();
            constructionWorkSiteBeanList.forEach(constructionWorkSiteBean -> {
                try {
                    String serialNumber = constructionWorkSiteBean.getObjId() + "-" + tempSerialNumber;
                    GrantCodeUtil.checkPeriodValidity(privateKey, constructionWorkSiteBean.getGrantCode(), serialNumber);
                } catch (GeneralSimpleException e) {
                    log.error("场站授权失败, id:{}, name:{}", constructionWorkSiteBean.getObjId(), constructionWorkSiteBean.getSiteName(), e);
                    constructionWorkSiteBean.setIfGrant(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
                    workSiteIdList.add(constructionWorkSiteBean.getObjId());
                }
            });
            
            if(CollectionUtils.isNotEmpty(workSiteIdList)){
                this.baseMapper.updateIfGrantByIdIn(workSiteIdList);
            }
        }
    }

    /**
     * 校验场站授权
     *
     * @param constructionWorkSiteObjId 场站ID
     */
    @Override
    public void checkGrantByObjId(String constructionWorkSiteObjId) throws GeneralSimpleException {
        if(StringUtils.isBlank(constructionWorkSiteObjId)){
            return;
        }
        ConstructionWorkSiteBean constructionWorkSiteBean = getById(constructionWorkSiteObjId);
        if(Objects.isNull(constructionWorkSiteBean)){
            // 施工现场不存在
            throw new GeneralSimpleException("500007", constructionWorkSiteObjId);
        }

        String siteName = constructionWorkSiteBean.getSiteName();

        // 施工现场被删除
        if(StringUtils.equals(constructionWorkSiteBean.getIfDelete(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)){
            throw new GeneralSimpleException("500007", siteName);
        }
        
        // 无授权码
        if(StringUtils.isBlank(constructionWorkSiteBean.getGrantCode())){
            throw new GeneralSimpleException("500008", siteName);
        }
        
        // 授权到期
        if(StringUtils.equals(constructionWorkSiteBean.getIfGrant(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)){
            throw new GeneralSimpleException("500009", siteName);
        }

        String serialNumber = constructionWorkSiteBean.getObjId() + "-" + getSerialNumber();
        GrantCodeUtil.checkPeriodValidity(privateKey, constructionWorkSiteBean.getGrantCode(), serialNumber);
    }

    /**
     * 根据施工现场ID查询授权的场站
     *
     * @param workSiteIdList 现场ID
     * @return 授权的现场
     */
    @Override
    public List<String> findGrantSiteByObjIdIn(List<String> workSiteIdList) {
        List<ConstructionWorkSiteBean> workSiteBeanList = this.lambdaQuery().in(ConstructionWorkSiteBean::getObjId, workSiteIdList)
                .eq(ConstructionWorkSiteBean::getIfGrant, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                .isNotNull(ConstructionWorkSiteBean::getGrantCode).ne(ConstructionWorkSiteBean::getGrantCode, "")
                .eq(ConstructionWorkSiteBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .list();
        if(CollectionUtils.isNotEmpty(workSiteBeanList)){
            return workSiteBeanList.stream().map(ConstructionWorkSiteBean::getObjId).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    /**
     * 根据工程ID查询施工现场ID
     *
     * @param workIdList 工程ID
     * @return 施工现场ID
     */
    @Override
    public List<String> findGrantSiteByWorkIdIn(List<String> workIdList) {
        List<ConstructionWorkSiteBean> workSiteBeanList = this.lambdaQuery()
                .in(ConstructionWorkSiteBean::getConstructionWorkObjId, workIdList)
                .eq(ConstructionWorkSiteBean::getIfGrant, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                .isNotNull(ConstructionWorkSiteBean::getGrantCode).ne(ConstructionWorkSiteBean::getGrantCode, "")
                .eq(ConstructionWorkSiteBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .list();
        if(CollectionUtils.isNotEmpty(workSiteBeanList)){
            return workSiteBeanList.stream().map(ConstructionWorkSiteBean::getObjId).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    /**
     * 获取机器码
     * @return 机器码
     */
    private String getSerialNumber(){
        String realTimeSerialNumber = Constants.realTimeSerialNumber;
        if(StringUtils.isBlank(realTimeSerialNumber)){
            realTimeSerialNumber = AuthorizationUtils.serialNumber();
            if(StringUtils.isBlank(realTimeSerialNumber)){
                try {
                    realTimeSerialNumber = StringUtils.trim(CommonUtils.sendGet(serialNumberUrl));
                } catch (GeneralSimpleException e) {
                    log.error("系统序列号获取异常", e);
                    throw new RuntimeException("系统序列号获取异常，请检查number服务有无启动！");
                }
            }
            if(StringUtils.isNotBlank(realTimeSerialNumber)){
                Constants.realTimeSerialNumber = realTimeSerialNumber;
            }else{
                throw new RuntimeException("系统序列号获取失败，请检查number服务有无启动！");
            }
        }
        return realTimeSerialNumber;
    }
}
